<template>
  <div class="main-container">
    <div class="route-container">
      <router-view v-slot="{ Component }">
        <keep-alive :include="cachedViews">
          <component :is="markRawComponent(Component)" :key="$route.path" />
        </keep-alive>
      </router-view>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import { markRaw } from 'vue'
import useAuthStore from "@/stores/modules/auth.ts";
// import useLayoutStore from "@/stores/modules/layout.ts";

const authStore = useAuthStore()
// const layoutStore = useLayoutStore()
const route = useRoute()

// 缓存的路由视图列表
const cachedViews = computed(() => {
  const menuList = authStore.showMenuList || []
  const cacheList = []
  
  // 递归查找需要缓存的路由组件
  const findCacheRoutes = (menus) => {
    menus.forEach(menu => {
      if (menu.meta?.isKeepAlive=='1' && menu.name) {
        cacheList.push(menu.name)
      }
      if (menu.children && menu.children.length > 0) {
        findCacheRoutes(menu.children)
      }
    })
  }
  
  findCacheRoutes(menuList)
  return cacheList
})

// 包装组件以防止响应式
const markRawComponent = (Component) => {
  return Component ? markRaw(Component) : null
}

// 根据路由路径查找对应的菜单项
const findMenuItemByPath = (path, menuItems) => {
  if (!menuItems) return null

  for (const item of menuItems) {
    if (item.path === path) return item

    if (item.children) {
      const found = findMenuItemByPath(path, item.children)
      if (found) return found
    }
  }
  return null
}

// 监听路由变化
watch(
  () => route.path,
  (newPath) => {
    const menuItem = findMenuItemByPath(newPath, authStore.showMenuList)
    if (menuItem) {
      // 可以在这里添加路由变化时的其他处理逻辑
    }
  },
  { immediate: true }
)

// 初始化菜单状态
const initMenuStatus = async () => {
  const currentPath = route.path
  const menuItem = findMenuItemByPath(currentPath, authStore.showMenuList)
  if (menuItem) {
    // 可以在这里添加初始化时的其他处理逻辑
  }
}

onMounted(() => {
  initMenuStatus()
})
</script>

<style lang="scss" scoped>
.main-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
    // 全局字体
  font-family: "KoiFont", Helvetica, "PingFang SC", "Microsoft Yahei",'Alimama ShuHeiTi', sans-serif;
  // 修改图标
  // cursor: url("../assets/mouse/index.cur"), auto !important;
  word-break: break-word;
  .route-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 2;
    // pointer-events: none;
    overflow: auto;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    will-change: transform;

    &:fullscreen {
      width: 100vw;
      height: 100vh;
      background: #fff;
      pointer-events: auto;
      transform: translateZ(0); 
      backface-visibility: hidden; 
    }

    >* {
      pointer-events: auto;
      transition: inherit;
    }
  }
}
</style>